import axios from 'axios'
import type { AxiosError, } from 'axios'
import { ElMessage } from 'element-plus'

import useUserStore from '@/store/modules/user'

const serve = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5 * 1000
})

serve.interceptors.request.use(
  (config) => {

    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.token = userStore.token
    }

    return config
  },
  (error: AxiosError) => {
    ElMessage({
      type: 'error',
      message: error.message
    })

    return Promise.reject(error)
  }
)

serve.interceptors.response.use(
  (response) => {
    const { code, message } = response.data

    // 根据自定义错误码判断请求是否成功
    if (code === 200) {
      // 将组件用的数据返回
      return response.data
    } else {
      // 处理业务错误。
      ElMessage({
        type: 'error',
        message: message
      })
      return Promise.reject(new Error(message))
    }
  },
  (error: AxiosError) => {
    let message = ''
    const status = error.response?.status
    switch (status) {
      case 401:
        message = 'TOKEN过期'
        break
      case 403:
        message = '无权访问'
        break
      case 404:
        message = '请求地址错误'
        break
      case 500:
        message = '服务器出现问题'
        break
      default:
        message = '网络出现问题'
        break
    }
    ElMessage({
      type: 'error',
      message
    })

    return Promise.reject(error)
  }
)

export default serve

